//
//  ExchangeRateTableViewController.m
//  汇率换算
//
//  Created by king on 15/11/26.
//  Copyright © 2015年 king. All rights reserved.
//

#import "ExchangeRateTableViewController.h"
#import "ExchangeRateConvert.h"
#import "ExchangeRateCodeFormTableViewCell.h"
#import "ExchangeRateToCurrencyTableViewCell.h"
#import "ExchangeRateDetailTableViewController.h"

@interface ExchangeRateTableViewController ()<UITextFieldDelegate>

@end

@implementation ExchangeRateTableViewController

#pragma mark - Method viewWillAppear:
- (void)viewWillAppear:(BOOL)animated {
    [self exchangeRateButton];
    [self.tableView reloadData];
}
#pragma mark - Method viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置title
    self.title = @"汇率兑换";
    // 设置转换按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"exchange" style:UIBarButtonItemStyleDone target:self action:@selector(exchangeRateButton)];
    
    // 设置初始值
    [self setInitialValue];
    
    //  注册cell
    [self.tableView registerClass:[ExchangeRateCodeFormTableViewCell class] forCellReuseIdentifier:@"exchangeRateCovertResues"];
    [self.tableView registerClass:[ExchangeRateToCurrencyTableViewCell class] forCellReuseIdentifier:@"exchangeRateToCurrencyCell"];
}
#pragma mark - Method setInitialValue(设置初始值)
- (void)setInitialValue {
    self.temp = [[ExchangeRateConvertDetailModel alloc] init];
    self.temp.fromCurrency = @"CNY";
    self.temp.toCurrency = @"USD";
    self.temp.amount = @1;
}
#pragma mark - Method exchangeRateButton:
- (void)exchangeRateButton {
    NSString *str = ((UITextField *)[self.view viewWithTag:1000]).text;
    self.temp.amount = @([str integerValue]);
    NSString *httpArg = [NSString stringWithFormat:@"fromCurrency=%@&toCurrency=%@&amount=%@", self.temp.fromCurrency, self.temp.toCurrency, self.temp.amount];
    NSString *httpUrl = @"http://apis.baidu.com/apistore/currencyservice/currency";
    [self request: httpUrl withHttpArg: httpArg];
}
-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"1ba9e11c1173ba7418fa8e0329cce543" forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
       if (error) {
           NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
       } else {
           
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
           NSLog(@"789098765%@", dic[@"retData"][@"currency"]);
           NSLog(@"789098765%@", [dic[@"retData"][@"currency"] class]);
           self.temp = [[ExchangeRateConvertDetailModel alloc] init];
           [self.temp setValuesForKeysWithDictionary:dic[@"retData"]];
           [self.tableView reloadData];
           NSLog(@"%@", dic);
       }
    }];
}
#pragma mark - Method didReceiveMemoryWarning
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
//    NSString *str
}
#pragma mark - Method Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
#pragma mark - Method tableView:numberOfRowsInSection:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
#pragma mark - Method tableView:cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        ExchangeRateCodeFormTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"exchangeRateCovertResues" forIndexPath:indexPath];
        cell.model = self.temp;
        cell.amountText.delegate = self;
        return cell;
    } else {
        ExchangeRateToCurrencyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"exchangeRateToCurrencyCell" forIndexPath:indexPath];
        cell.model = self.temp;
        cell.currencyText.delegate = self;
        cell.convertedamountText.delegate = self;
        return cell;
    }
    return nil;
}
#pragma mark - Method textFieldShouldBeginEditing(textField 不可被编辑)
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.tag == 1000) {
        return YES;
    } else {
        return NO;
    }
}
#pragma mark - Method tableView:heightForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
#pragma mark - Method tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ExchangeRateDetailTableViewController *controller = [[ExchangeRateDetailTableViewController alloc] init];
    controller.currencyType = indexPath.row;
    [self.navigationController pushViewController:controller animated:YES];
}

@end
